# # import time
# #
# # def func1():
# #
# #     for i in range(11):
# #         yield
# #         print('这是我第%s次打印啦' % i)
# #         time.sleep(1)
# #
# #
# # def func2():
# #     g = func1()
# #     #next(g)
# #     for k in range(10):
# #
# #         print('哈哈，我第%s次打印了' % k)
# #         time.sleep(1)
# #         next(g)
#
# #不写yield，下面两个任务是执行完func1里面所有的程序才会执行func2里面的程序，
# # 有了yield，我们实现了两个任务的切换+保存状态
# # func1()
# # func2()
#
#
# # 计算密集型：串行与协程的效率对比
# # import time
# #
# # def task1():
# #     res = 1
# #     for i in range(1,100000):
# #         res += i
# #
# #
# # def task2():
# #     res = 1
# #     for i in range(1,100000):
# #         res -= i
# #
# # start_time = time.time()
# # task1()
# # task2()
# # print(f'串行消耗时间:{time.time()-start_time}')  # 串行消耗时间:0.012000560760498047
#
#
# import time
#
#
# def task1():
#     res = 1
#     for i in range(1, 100000):
#         res += i
#         yield res
#
#
# def task2():
#     g = task1()
#     res = 1
#     for i in range(1, 100000):
#         res -= i
#         next(g)
#
#
# start_time = time.time()
# task2()
# print(f'协程消耗时间:{time.time() - start_time}')  # 协程消耗时间:0.0260012149810791

#
# from greenlet import greenlet
# import time
#
# # 不能自动切换,
# # 遇到IO不切换
# # 可以保持原来的状态.
# def eat(name):
#
#     print('%s eat 1' %name)  #2
#     g2.switch('alex')   #3
#     time.sleep(3)
#     print('%s eat 2' %name) #6
#     g2.switch() #7
#
# def play(name):
#     print('%s play 3' %name) #4
#     g1.switch()      #5
#     print('%s play 4' %name) #8
#
# g1 = greenlet(eat)
# g2 = greenlet(play)
#
# g1.switch('太白')  # 1  第一次切换一定要传参
#
# # g2.switch('b1')
#
# # time.sleep(300)

# 还没有做到真正遇到IO切换
#
# import gevent
# import time
# def eat(name):
#     print('%s eat 1' %name)  # 1
#     # gevent.sleep(2)
#     time.sleep(300)
#     print('%s eat 2' %name)
#
# def play(name):
#     print('%s play 1' %name)  # 2
#     # gevent.sleep(1)
#     time.sleep(3)
#     print('%s play 2' %name)
#
#
# g1 = gevent.spawn(eat, 'alex')
# g2 = gevent.spawn(play, name='taibai')
# # g1.join()
# # g2.join()
# #或者gevent.joinall([g1,g2])
# gevent.joinall([g1,g2])
# print('主')



import threading
from gevent import monkey
monkey.patch_all()  # 将你代码中的所有的IO都标识.

import gevent  # 直接导入即可
import time
def eat():
    print(f'线程1:{threading.current_thread().getName()}')
    print('eat food 1')
    time.sleep(3)  # 加上mokey就能够识别到time模块的sleep了
    print('eat food 2')

def play():
    print(f'线程2:{threading.current_thread().getName()}')
    print('play 1')
    time.sleep(1)  # 来回切换，直到一个I/O的时间结束，这里都是我们个gevent做得，不再是控制不了的操作系统了。
    print('play 2')

g1=gevent.spawn(eat)
g2=gevent.spawn(play)
gevent.joinall([g1,g2])
print(f'主:{threading.current_thread().getName()}')
